﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace Macaw.Moss2007.CustomErrorPageSolution
{
    public abstract class CustomErrorPageHelper
    {
        public const string CUSTOMERRORPAGEURL = "CustomErrorPageUrl";
 
        private static string GetWebPropertyRecursive(Guid siteid, Guid webid, string propertyname)
        {
            Guid curwebid = webid;
            while (!Guid.Empty.Equals( curwebid ))
            {
                using (SPSite site = new SPSite(siteid))
                {
                    using (SPWeb web = site.OpenWeb(webid))
                    {
                        if (web.Properties.ContainsKey(propertyname))
                        {
                            return web.Properties[propertyname];
                        }
                        curwebid = web.ParentWebId;
                    }
                }
            }
            return null;
        }


        public static string GetCustomErrorPageUrl(Guid siteid, Guid webid, bool recursive)
        {
            if (recursive)
            {
                return GetWebPropertyRecursive(siteid , webid, CUSTOMERRORPAGEURL);
            }
            else
            {
                using (SPSite site = new SPSite(siteid))
                {
                    using (SPWeb web = site.OpenWeb(webid))
                    {
                        return web.Properties[CUSTOMERRORPAGEURL];
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="web"></param>
        /// <param name="enabled"></param>
        public static void SetCustomErrorPageUrl(SPWeb web, string url)
        {
            if (url == null)
            {
                web.Properties.Remove(CUSTOMERRORPAGEURL);
            }
            else
            {
                web.Properties[CUSTOMERRORPAGEURL] = url;
            }
            web.Properties.Update();
        }

    }
}
